//
//  BanBu_MagicCastViewController.m
//  Koochat
//
//  Created by 张毅飞 on 14-9-16.
//
//

#import "BanBu_MagicCastViewController.h"
#import "BanBu_ImageView.h"
#import "BanBu_MagicView.h"
#import "TKLoadingView.h"
#import "BanBu_TextAndTags.h"
#import "NSData+Base64.h"
#import "BanBu_BroadcastTVC.h"
#import "BanBu_TextAndTags.h"
@interface BanBu_MagicCastViewController ()<UITextViewDelegate,UIScrollViewDelegate,UIWebViewDelegate,BanBuRequestDelegate>
{
    UITextView * _inputView;
    UIScrollView * _scrollView;
    UIPageControl * _pageControl;
    UIWebView * _preWebView;
    NSMutableString * _htmlStr;
    UIButton * _sendButton;
    
    NSData * _imgData;
    NSData * _voiceData;
    NSString * _voiceTime;
    NSString * _imgString;
    NSString * _voiceString;
}
@end

@implementation BanBu_MagicCastViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)dealloc
{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [_inputView release];
    _inputView = nil;
    [_scrollView release];
    _scrollView = nil;
    [_pageControl release];
    [_preWebView release];
    _pageControl = nil;
    _preWebView = nil;
    [_htmlStr release];
    _htmlStr=nil;
    [_imgString release];
    _imgString=nil;
    [_imgData release];
    _imgData =nil;
    
    [_voiceData release];
    _voiceData = nil;
    [_voiceTime release];
    _voiceTime = nil;
    [_voiceString release];
    _voiceString = nil;
    [super dealloc];
}
-(id)initWithImageData:(NSData *)imgData WithVoiceData:(NSData *)voiceData WithVoiceTime:(NSString *)voiceTime
{
    self=[super init];
    if (self) {
        _imgData=[[NSData alloc]initWithData:imgData];
        if (voiceData) {
            _voiceData=[[NSData alloc]initWithData:voiceData];
            _voiceTime=[[NSString alloc]initWithString:voiceTime]; 
        }
     }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    BanBu_ImageView * img = [[BanBu_ImageView alloc]initWithBackGroundImageType:UIImageViewCreatTypeTable];
  
    self.view.backgroundColor = [UIColor colorWithPatternImage:img.image];
    [img release];
    _htmlStr=[[NSMutableString alloc]init];
    _inputView = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, 300, 130)];
    _inputView.font=[UIFont systemFontOfSize:13];
    _scrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 200, 320, self.view.bounds.size.height-160)];
    [self.view addSubview:_inputView];
    [self.view addSubview:_scrollView];
    
    //预览框
    _preWebView=[[UIWebView alloc] initWithFrame:CGRectMake(10, 215, 280, 230)];
    _preWebView.delegate=self;
    [self.view addSubview:_preWebView];
    _preWebView.hidden=YES;
    //增加边框
    [ _preWebView.layer setMasksToBounds:YES];
    [_preWebView.layer setBorderWidth:1.0];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0, 0, 0, 1 });
    [_preWebView.layer setBorderColor:colorref];
    [_preWebView.layer setCornerRadius:5];
    
    //2014年10月28日14:49:47 by 张毅飞 适配4S，pad⬇️
    CGFloat screenHei = [UIScreen mainScreen].applicationFrame.size.height;
    if (screenHei<500) {
        _inputView.frame=CGRectMake(10, 5, 300, 50);
        _scrollView.frame=CGRectMake(0, _inputView.frame.size.height+60, 320, self.view.frame.size.height-100);
        
    }
    [self setUp1];
    if (screenHei<500) {
        _pageControl.frame=CGRectMake(100, self.view.frame.size.height-90, 120, 30);
    }
//⬆️
}
-(void)setUp1
{
    _inputView.textColor = [UIColor blackColor];
    _inputView.font = [UIFont systemFontOfSize:18];
    _inputView.layer.borderColor = [[UIColor grayColor] CGColor];
    _inputView.layer.borderWidth = 1.0;
    _inputView.layer.cornerRadius = 4.0;
    _inputView.returnKeyType = UIReturnKeyDefault;
    _inputView.keyboardType = UIKeyboardTypeDefault;
    _inputView.backgroundColor = [UIColor whiteColor];
    _inputView.delegate = self;
//127	176	240
    //预览更多素材按钮
    NSArray *array=[[NSArray alloc] initWithObjects:NSLocalizedString(@"magicMoreMaterial", nil),NSLocalizedString(@"magicPreview", nil), nil];
    for (int i=0; i<2; i++) {
        UIButton *btn=[UIButton buttonWithType: UIButtonTypeRoundedRect];
        if ([UIScreen mainScreen].applicationFrame.size.height<500) {
            btn.frame=CGRectMake(10+155*i, _inputView.frame.size.height+10  , 145, 40);
        }
        else
            btn.frame=CGRectMake(10+155*i, _inputView.frame.size.height +20 , 145, 40);

        btn.tag=i+100;
        [btn.layer setCornerRadius:7];
        btn.backgroundColor=[UIColor colorWithRed:127/255.0 green:176/255.0 blue:240/255.0 alpha:1];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(previewAndMore:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    }
    //发送按钮
    _sendButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    _sendButton.frame=CGRectMake(0, 0, 40, 25);
    [_sendButton addTarget:self action:@selector(completionAction) forControlEvents:UIControlEventTouchUpInside];
    [_sendButton setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
    [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem * right=[[UIBarButtonItem alloc]initWithCustomView:_sendButton];
    self.navigationItem.rightBarButtonItem=right;
    [right release];
    _sendButton.hidden=YES;
    
    NSUserDefaults * def=[NSUserDefaults standardUserDefaults];
    NSDictionary * magicImagePathDic=[def objectForKey:@"magicWords"];
    NSArray * smaleImagePathArray = [magicImagePathDic valueForKey:@"dlist"];
 //   NSArray * bigImagePathArray = [magicImagePathDic valueForKey:@"jlist"];
    _pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(100, 480, 120, 30)];
    _pageControl.numberOfPages=(smaleImagePathArray.count/25)+(smaleImagePathArray.count%5?1:0);
    
    [self.view addSubview:_pageControl];
    
    int index = 0;
    int line=0;
    int page = 0;
    for (NSDictionary * aMagicDic in smaleImagePathArray)
    {
        BanBu_MagicView * imageView = [[BanBu_MagicView alloc]init];
        
        imageView.backgroundColor = [UIColor clearColor];
        imageView.userInteractionEnabled = YES;
        CGRect frame=CGRectMake((10+62*index)+320*page, line*59, 52, 52);
        imageView.frame = frame;
        
        [imageView setImageViewFrame:YES];
        
        imageView.imageView.idStr = [aMagicDic valueForKey:@"id"];
        imageView.imageView.bigUrl = [aMagicDic valueForKey:@"full"];
        
        //添加点击事件
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnAction:)
                                        ];
        [imageView addGestureRecognizer:tap];
        [tap release];
        
        NSString * imageUrl = [aMagicDic valueForKey:@"file"];
        
        [imageView.imageView setImageWithUrlString:imageUrl withFolderName:@"MagicWords"];
        
        [_scrollView addSubview:imageView];
        [imageView release];
        
        index ++;
        if (index%5==0&&index!=0) {
            index=0;
            ++line;
        }
        if (line%5==0&&line!=0) {
            ++page;
            line=0;
        }
    }
    
    CGSize smallSize=CGSizeMake(320*(smaleImagePathArray.count/25+(smaleImagePathArray.count%25?1:0)), _scrollView.frame.size.height);
    _scrollView.contentSize=smallSize;
    _scrollView.pagingEnabled=YES;
    _scrollView.showsHorizontalScrollIndicator=NO;
    _scrollView.delegate=self;

}

#pragma mark - 完成，发送
-(void)completionAction
{
    //先上传图片
    NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:1];
    [sendDic setValue:@"jpg" forKey:@"extname"];
    [AppComManager uploadBanBuBroadcastMedia:_imgData mediaName:@"tupian.jpg" par:sendDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    self.navigationController.view.userInteractionEnabled = NO;
  //
}
#pragma mark -
#pragma mark 点击小图
-(void)btnAction:(UITapGestureRecognizer *)tap
{
    [_inputView resignFirstResponder];
    BanBu_MagicView * imageView = (BanBu_MagicView *)tap.view;
    
    NSString * idStr = imageView.imageView.idStr;
//    
//       _inputView.text = [NSString stringWithFormat:@"%@[%@]",_inputView.text,idStr];
//   // _inputView.font=[UIFont systemFontOfSize:13];
    NSMutableString * textStr=[NSMutableString stringWithString:_inputView.text];
    [textStr insertString:[NSString stringWithFormat:@"[%@]",idStr] atIndex:_inputView.selectedRange.location];
    _inputView.text = [NSString stringWithFormat:@"%@",textStr];
    
    if (_inputView.contentOffset.y+130<=_inputView.contentSize.height) {
        _inputView.contentOffset=CGPointMake(0, _inputView.contentSize.height-130);
    }

}
#pragma mark-
#pragma mark 点击预览和更多素材
-(void)previewAndMore:(UIButton *)button
{
    if(button.tag==100)
    {
        [_inputView resignFirstResponder];
        _preWebView.hidden=YES;
        _scrollView.hidden=NO;
        _pageControl.hidden=NO;
        _sendButton.hidden=YES;
    }
    //预览
    else if(button.tag==101)
    {
        _scrollView.hidden=YES;
         _preWebView.hidden = NO;
        _pageControl.hidden=YES;
        [_inputView resignFirstResponder];
        
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
        self.navigationController.view.userInteractionEnabled = NO;
        
        NSMutableDictionary * pardic = [NSMutableDictionary dictionaryWithCapacity:8];
        [pardic setValue:_inputView.text forKey:@"magictext"];
        
        [AppComManager getMagicWordsHtml:@"/_user_chat/_make_magic_chat_html.php?jsonfrom=" par:pardic delegate:self];
        _sendButton.hidden=NO;
    }
}

#pragma mark-
#pragma mark WebViewDelegate
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGRect frame = webView.frame;
    frame.size.height = 1;
    webView.frame = frame;
    
    CGSize fittingSize=[webView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    CGRect frame2=CGRectZero;
    frame2.size.height=frame.size.height+30;
    frame2.size.width=frame.size.width+30;
    
    if (fittingSize.height<=250) {
        _preWebView.frame=frame;
        webView.center=CGPointMake(160, 320);
    }
    else
    {
        _preWebView.frame=CGRectMake(10,215,300, 220);
    }

    
    //国外webView内存泄露解决办法，不知道真的假的
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];

}
#pragma mark -
#pragma mark ScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    _pageControl.currentPage=scrollView.contentOffset.x/320;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_inputView resignFirstResponder];
}

#pragma mark -
#pragma mark 显示预览
//显示预览
-(void)setContent:(NSString *)content
{
  //
    NSData * data = [NSData dataFromBase64String:content];
    //解析content；
  NSString * htmlStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    _htmlStr=[[NSMutableString stringWithFormat:@"%@",htmlStr] retain];
    [_preWebView loadHTMLString:htmlStr baseURL:nil];
   
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    [htmlStr release];
}

#pragma mark -
#pragma mark RequestDelegate
-(void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:1];
    [TKLoadingView dismissTkFromView:self.view animated:NO afterShow:1];
    self.navigationController.view.userInteractionEnabled = YES;
    
    if (error)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"", nil) activityAnimated:NO duration:1.3f];
    }
    
    if ([[resDic valueForKey:@"ok"] boolValue]&&[[resDic valueForKey:@"fc"] isEqualToString:@"make_magic_chat_html"])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            //显示
            [self setContent:[resDic valueForKey:@"magictext"]];
        });
    }
    if ([[resDic valueForKey:@"fc"] isEqualToString:@"send_broad_cast"]) {
   //     [self.navigationController popToRootViewControllerAnimated:YES];
        [self performSelector:@selector(backAndRefresh:) withObject:resDic afterDelay:0];
    }
    
    
}
#pragma mark - 返回并刷新
-(void)backAndRefresh:(NSDictionary *)dic
{
    if (![[dic valueForKey:@"fc"]isEqualToString:@"make_magic_chat_html"]) {
        for(BanBu_BroadcastTVC *v in self.navigationController.viewControllers)
        {
            if([v isKindOfClass:[BanBu_BroadcastTVC class]])
            {
                [v setRefreshing];
            }
        }
        [self.navigationController popToRootViewControllerAnimated:YES];

    }
    
}
#pragma mark - banbuUploadRequest
//上传图片回调方法
-(void)banbuUploadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    [TKLoadingView dismissTkFromView:self.view animated:NO afterShow:0.0];
    if(error){
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"uploadFailNotice", nil) activityAnimated:NO duration:2.0];
    }
    if ([[resDic valueForKey:@"ok"] boolValue]) {
        if([[resDic valueForKey:@"requestname"] isEqualToString:@"tupian.jpg"]){
            if (_imgString) {
                [_imgString release];
            }
            _imgString = [[NSString alloc]initWithString:[resDic valueForKey:@"fileurl"]];
            if (_voiceData) {
                 [self sendSound];
            }
            else
            {
                [self sendMessage];
            }
        }
        else
        {
            if(_voiceString){
                [_voiceString release];
            }
            _voiceString = [[NSString alloc]initWithString:[resDic valueForKey:@"fileurl"]];
            [FileManager removeItemAtPath:[AppComManager pathForMedia:@"yuyin.amr"] error:nil];
            [self sendMessage];

        }
    }
}

#pragma mark - sendMessage
-(void)sendMessage
{
    NSDictionary * attachDic=[[NSDictionary alloc]initWithObjectsAndKeys:@"image",@"type",_imgString,@"content", nil];
    NSMutableArray * attachArray=[[NSMutableArray alloc]initWithObjects:attachDic, nil];
    if(_voiceString){
        
        [attachArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"sound",@"type",_voiceString,@"content",_voiceTime,@"length", nil]];
    }
    //进行base64编码
    NSData * htmlData=[_htmlStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString * base64Str=[htmlData base64Encoding];
    
    base64Str = [self trimBlankString:base64Str];
    
    NSMutableDictionary * sendDic=[[NSMutableDictionary alloc]init];
    [sendDic setValue:attachArray forKey:@"attach"];
    [sendDic setValue:base64Str forKey:@"saytext"];
    [sendDic setValue:@"html" forKey:@"mkind"];
    NSDictionary * send=[NSDictionary dictionaryWithObject:sendDic forKey:@"says"];
    [AppComManager getBanBuData:BanBu_Send_Broadcast par:send delegate:self];
    [sendDic release];
}
#pragma mark -sendSonud
-(void)sendSound{
    
    NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:1];
    [sendDic setValue:@"amr" forKey:@"extname"];
    [AppComManager uploadBanBuBroadcastMedia:_voiceData mediaName:@"yuyin.amr" par:sendDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    self.navigationController.view.userInteractionEnabled = NO;
    //    [aTextView becomeFirstResponder];
    
}
#pragma mark - 去空行
//去掉空格、空行
-(NSString *)trimBlankString:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    return string;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
